package ru.cannabis.command.base;

import com.google.gson.Gson;
import ru.cannabis.command.AuthCommand;
import ru.cannabis.notification.JSONErrorResponse;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Администратор
 * Date: 23.02.13
 * Time: 17:48
 * To change this template use File | Settings | File Templates.
 */
public class CommandFactory
{
    private static final Logger log = LoggerFactory.getLogger(CommandFactory.class);
    private static Gson converter = new Gson();

    private static HashMap<String, Class<? extends AbstractCommand>> commands = new HashMap<String, Class<? extends AbstractCommand>>();
    {
        commands.put("auth", AuthCommand.class);
    }

    public AbstractCommand createFromJson(IoSession session, String jsonString)
    {
        String commandName = converter.fromJson(jsonString, JsonCommand.class).command;

        AbstractCommand command = null;
        Class<? extends AbstractCommand> clazz = commands.get(commandName);

        if (clazz != null)
        {
            try
            {
                command = clazz.newInstance();
                command.setSession(session);
                command.initParams(jsonString);
            }
            catch (Exception e)
            {
                log.error(String.format("Command for %s failed to be performed. request: ", session, jsonString));
                log.error(e.getMessage());
            }

            command.setName(commandName);
            return command;
        }
        else
        {
            log.error(String.format("Command for %s failed to be performed. request: ", session, jsonString));
        }
        return command;
    }

    public boolean writeToSession(IoSession session, String message)
    {
        if (session.isConnected())
        {
            session.write(message);
            return true;
        }
        return false;
    }

    public void writeToSession(IoSession session, AbstractCommand command)
    {
        writeToSession(session, converter.toJson(command.getResponse()));
    }

    public void writeToSession(IoSession session, JSONErrorResponse error)
    {
        writeToSession(session, converter.toJson(error));
    }
}
